package com.imooc.miaosha.util;

import com.imooc.miaosha.common.Const;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class CookieUtil {
    public static void writeCookie(HttpServletResponse response, String value) {
        Cookie cookie = new Cookie(Const.LOGIN_COOKIE_CONFIG.NAME, value);
        cookie.setDomain(Const.LOGIN_COOKIE_CONFIG.DOMAIN);
        cookie.setMaxAge(60 * 30);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
    }

    public static String readCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null||cookies.length==0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (StringUtils.equals(cookie.getName(), Const.LOGIN_COOKIE_CONFIG.NAME)) {
                return cookie.getValue();
            }
        }
        return null;
    }

    public static void deleteCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(Const.LOGIN_COOKIE_CONFIG.NAME)) {
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
    }
}
